package com.cat.dataStructure02;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/remove-k-digits/
 * @create 2025/10/21 16:59
 * @since JDK17
 */

public class Solution34 {
    public String removeKdigits(String num, int k) {
        int n = num.length(), top = 0;
        char[] stack = new char[n];
        for (var x : num.toCharArray()) {
            while (top > 0 && stack[top - 1] > x && k > 0) {
                top--;
                k--;
            }
            stack[top++] = x;
        }
        int i = 0;
        while (i < top - 1 && stack[i] == '0') {
            i++;
        }
        StringBuilder ans = new StringBuilder();
        for (; i < top - k; i++) {
            ans.append(stack[i]);
        }

        return ans.length() == 0 ? "0" : ans.toString();
    }
}
